package adsf.adminisadsf.gugedianzishichang;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

import adsf.adminisadsf.gugedianzishichang.fragment.BaseFragment;
import adsf.adminisadsf.gugedianzishichang.fragment.FragmentFactory;
import adsf.adminisadsf.gugedianzishichang.utils.PagerTab;
import adsf.adminisadsf.gugedianzishichang.utils.UIUtils;

public class MainActivity extends BaseActivity {

    private PagerTab mPagerTab;
    private ViewPager mViewPager;
    private MyAdapter myAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mPagerTab = (PagerTab) findViewById(R.id.pager_tab);
        mViewPager = (ViewPager) findViewById(R.id.viewPage);
        myAdapter = new MyAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(myAdapter);
        mPagerTab.setViewPager(mViewPager);//关联在一起
        mPagerTab.setOnPageChangeListener(new PagerTabChangeList());

    }

    //和framgmenta绑定数据
    class PagerTabChangeList implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

            BaseFragment fragment = FragmentFactory.createFragment(position);

            fragment.loadData();

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }


    //viewPager的数据源
    //如果viewpage的页面展示的是framgent的话就继承此类
    class MyAdapter extends FragmentPagerAdapter{

        private String[] mTabNames;

        public MyAdapter(FragmentManager fm) {
            super(fm);
            mTabNames = UIUtils.getStringArray(R.array.tab_names);
        }

        //返回页签标题
        @Override
        public CharSequence getPageTitle(int position) {
            return mTabNames[position];

        }

        //返回当前页面的framnget对象
        @Override
        public Fragment getItem(int position) {

            BaseFragment fragment = FragmentFactory.createFragment(position);

            return fragment;
        }

        //framgent的个数
        @Override
        public int getCount() {
            return mTabNames.length;
        }
    }
}
